/**
 * 3η ΓΕ 2013-2014 - Super Market
 * ΦΡΑΓΚΟΥΛΟΠΟΥΛΟΥ ΕΜΜΑΝΟΥΕΛΑ (69298)
 * ΧΑΛΔΑΣ ΧΑΡΑΛΑΜΠΟΣ (69305)
 * ΧΟΡΜΟΒΙΤΗΣ ΙΩΑΝΝΗΣ (69325)
 * ΧΟΥΣΤΟΥΛΑΚΗ ΕΥΑΓΓΕΛΙΑ (69327)
 */ 
package administratorGUI;

import java.util.Random;
import javax.persistence.TypedQuery;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.INFORMATION_MESSAGE;
import static javax.swing.JOptionPane.WARNING_MESSAGE;
import model.*;
import supermarket.EntityManagerFactory;
import supermarket.JTextFieldLimit;
import supermarket.LocalBanks;

/**
 * Οθόνη Εισαγωγής / Επεξεργασίας Πελάτη
 */
public class NewCustomerDialog extends javax.swing.JDialog {

    private LocalBanks localBanks = new LocalBanks();
    private boolean mSave = false;
    private boolean isNewRecord = true;
    private Customer customer;
    private String pointsCard;  // Αρ, Κάρτας Πόντων

    /**
     * Constructor
     */
    public NewCustomerDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        initForm();
        localBanks.fillCombo(bankCombo);
    }
    
    /**
     * Ορίζει το Max Length στα JTextFields
     */
    private void initForm() {
        lastName.setDocument(new JTextFieldLimit(40));
        firstName.setDocument(new JTextFieldLimit(30));
        address.setDocument(new JTextFieldLimit(50));
        password.setDocument(new JTextFieldLimit(20));
        holdersName.setDocument(new JTextFieldLimit(100));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        firstNameLabel = new javax.swing.JLabel();
        lastName = new javax.swing.JTextField();
        firstName = new javax.swing.JTextField();
        lastNameLabel = new javax.swing.JLabel();
        creditCardPanel = new javax.swing.JPanel();
        bankLabel = new javax.swing.JLabel();
        bankCombo = new javax.swing.JComboBox();
        creditCardLabel = new javax.swing.JLabel();
        cvvLabel = new javax.swing.JLabel();
        cvv = new javax.swing.JFormattedTextField();
        ownerLabel = new javax.swing.JLabel();
        holdersName = new javax.swing.JTextField();
        creditCard = new javax.swing.JFormattedTextField();
        passwordLabel = new javax.swing.JLabel();
        password = new javax.swing.JTextField();
        addressLabel = new javax.swing.JLabel();
        address = new javax.swing.JTextField();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Προφίλ Πελάτη");
        setResizable(false);

        firstNameLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        firstNameLabel.setText("Όνομα");

        lastName.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        firstName.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        lastNameLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lastNameLabel.setText("Επώνυμο");

        creditCardPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED), "ΣΤΟΙΧΕΙΑ ΠΙΣΤΩΤΙΚΗΣ ΚΑΡΤΑΣ", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 3, 12))); // NOI18N

        bankLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        bankLabel.setText("Τράπεζα");

        bankCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        bankCombo.setSelectedIndex(-1);
        bankCombo.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        creditCardLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        creditCardLabel.setText("Αριθμός Πιστωτικής Κάρτας");

        cvvLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        cvvLabel.setText("CVV");

        cvv.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        cvv.setColumns(3);
        try {
            cvv.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        ownerLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        ownerLabel.setText("Όνομα κατόχου");

        holdersName.setColumns(40);
        holdersName.setAutoscrolls(false);
        holdersName.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        creditCard.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        creditCard.setColumns(16);
        try {
            creditCard.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####-######-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        org.jdesktop.layout.GroupLayout creditCardPanelLayout = new org.jdesktop.layout.GroupLayout(creditCardPanel);
        creditCardPanel.setLayout(creditCardPanelLayout);
        creditCardPanelLayout.setHorizontalGroup(
            creditCardPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(creditCardPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(creditCardPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(holdersName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 379, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(creditCardPanelLayout.createSequentialGroup()
                        .add(creditCardPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(ownerLabel)
                            .add(creditCardPanelLayout.createSequentialGroup()
                                .add(creditCardPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(bankCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 158, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(bankLabel))
                                .add(18, 18, 18)
                                .add(creditCardPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
                                    .add(creditCardLabel)
                                    .add(creditCard, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 152, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                        .add(18, 18, 18)
                        .add(creditCardPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
                            .add(cvvLabel)
                            .add(cvv, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(17, Short.MAX_VALUE))
        );
        creditCardPanelLayout.setVerticalGroup(
            creditCardPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(creditCardPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(creditCardPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(bankLabel)
                    .add(creditCardLabel)
                    .add(cvvLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(creditCardPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(bankCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(creditCard, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(cvv, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(ownerLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(holdersName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        creditCardPanelLayout.linkSize(new java.awt.Component[] {creditCard, cvv, holdersName}, org.jdesktop.layout.GroupLayout.VERTICAL);

        passwordLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        passwordLabel.setText("Password");

        password.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        addressLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        addressLabel.setText("Διεύθυνση");

        address.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        cancelButton.setText("Ακύρωση");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setText("Εγγραφή");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(mainPanelLayout.createSequentialGroup()
                        .add(22, 22, 22)
                        .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(passwordLabel)
                            .add(addressLabel)
                            .add(firstNameLabel)
                            .add(lastNameLabel)
                            .add(password, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 211, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(address, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 420, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(mainPanelLayout.createSequentialGroup()
                            .addContainerGap()
                            .add(lastName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 420, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(org.jdesktop.layout.GroupLayout.LEADING, mainPanelLayout.createSequentialGroup()
                            .add(22, 22, 22)
                            .add(firstName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 420, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, mainPanelLayout.createSequentialGroup()
                            .add(258, 258, 258)
                            .add(saveButton)
                            .add(30, 30, 30)
                            .add(cancelButton))
                        .add(mainPanelLayout.createSequentialGroup()
                            .addContainerGap()
                            .add(creditCardPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(24, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(lastNameLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(lastName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(firstNameLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(firstName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(addressLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(address, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(11, 11, 11)
                .add(passwordLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(password, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(29, 29, 29)
                .add(creditCardPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(15, 15, 15)
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(cancelButton)
                    .add(saveButton))
                .addContainerGap())
        );

        mainPanelLayout.linkSize(new java.awt.Component[] {address, firstName, lastName, password}, org.jdesktop.layout.GroupLayout.VERTICAL);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(mainPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(mainPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Button: Ακύρωση
     *
     * @param evt
     */
     private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
         dispose();
         mSave = false;
     }//GEN-LAST:event_cancelButtonActionPerformed

     /**
      * Button: Εγγραφή
      * @param evt 
      */
     private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        // Έλεγχος για υποχρεωτικά πεδία
         String field = "";

         if (lastName.getText().trim().isEmpty()) {
             field = lastNameLabel.getText();
         } else if (firstName.getText().trim().isEmpty()) {
             field = firstNameLabel.getText();
         } else if (password.getText().trim().isEmpty()) {
             field = passwordLabel.getText();
         }

         if (!field.isEmpty()) {
             JOptionPane.showMessageDialog(this, "Το πεδίο '" + field
                     + "' είναι υποχρεωτικό.", "Καταχώρηση", WARNING_MESSAGE);
         } else {
             if (isNewRecord) {
                 pointsCard = createPointsCardNumber();
                 JOptionPane.showMessageDialog(this, "Εκδόθηκε νέα Κάρτα " +
                         "Πόντων με αριθμό: " + pointsCard,
                         "Κάρτα πόντων", INFORMATION_MESSAGE);
                 
             }
             mSave = true;
             dispose();
         }
     }//GEN-LAST:event_saveButtonActionPerformed

     /**
      * Δημιουργεί και επιστρέφει έναν Αριθμό Κάρτας Πόντων της μορφής ###-###
      * Ελέγχει αν ο αριθμός υπάρχει ήδη στη βάση, ώστε να είναι μοναδικός
      * @return 
      */
     private String createPointsCardNumber () {
         String number = "###-###"; // dummy initial value
         boolean isUnique = false;
         
         Random r = new Random();
         
         // loop μέχρι να βρω μοναδικο αριθμό κάρτας
         while (number.equals("###-###") || !isUnique) {
            number = String.format("%03d-%03d", r.nextInt(999),
                                                r.nextInt(999)); 
         
            // Ελέγχω αν υπάρχει Πελάτης με την ίδια κάρτα
            TypedQuery<Customer> query = EntityManagerFactory.getEntityManager()
                       .createNamedQuery("Customer.findByPointsCardNumber", 
                       Customer.class).setParameter("pointsCardNumber", number);

            
            isUnique = query.getResultList().isEmpty();
         }
         return number;
     }
     /**
      * Επιστρέφει το Όνομα του Πελάτη
      * @return 
      */
    public String getFirstName() {
        return firstName.getText();
    }

    /**
     * Επιστρέφει το Επώνυμο του Πελάτη
     * @return 
     */
    public String getLastName() {
        return lastName.getText();
    }

    /**
     * Επιστρέφει τη Διεύθυνση του Πελάτη
     * @return 
     */
    public String getAddress() {
        return address.getText();
    }

    /**
     * Επιστρέφει το Password του Πελάτη
     * @return 
     */
    public String getPassword() {
        return password.getText();
    }
    
    /**
     * Επιστρέφει τον Αριθμό της Κάρτας Πόντων
     * @return 
     */
    public String getPointsCard() {
        return pointsCard;
    }

    /**
     * Επιστρέφει τον Αριθμό της Πιστωτικής Κάρτας
     * @return 
     */
    public String getCreditCard() {
        return creditCard.getText();
    }

    /**
     * Επιστρέφει το CVV της Πιστωτικής Κάρτας
     * @return 
     */
    public String getCVV() {
        return cvv.getText();
    }

    /**
     * Επιστρέφει την επιλεγμένη τράπεζα
     * @return 
     */
    public String getBank() {
        return (String) (bankCombo.getSelectedItem());
    }

    /**
     * Επιστρέφει το όνομα του Κατόχου της Πιστωτικής Κάρτας
     * @return 
     */
    public String getHoldersName() {
        return holdersName.getText();
    }

    public boolean isValidForSave() {
        return mSave;
    }

    /**
     * Γεμίζει τα πεδία της οθόνης (σε edit mode)
     * @param customer Customer
     */
    public void setCustomer(Customer customer) {
        this.customer = customer;
        this.isNewRecord = false;
        
        lastName.setText(customer.getLastName());
        firstName.setText(customer.getFirstName());
        address.setText(customer.getAddress());
        password.setText(customer.getPassword());
        pointsCard = customer.getPointsCardNumber();
        
        creditCard.setText(customer.getCreditCardNum());
        bankCombo.setSelectedIndex(localBanks.getBankdId(customer.getBank()));
        cvv.setText(customer.getCvv());
        holdersName.setText(customer.getOwner());
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField address;
    private javax.swing.JLabel addressLabel;
    private javax.swing.JComboBox bankCombo;
    private javax.swing.JLabel bankLabel;
    private javax.swing.JButton cancelButton;
    private javax.swing.JFormattedTextField creditCard;
    private javax.swing.JLabel creditCardLabel;
    private javax.swing.JPanel creditCardPanel;
    private javax.swing.JFormattedTextField cvv;
    private javax.swing.JLabel cvvLabel;
    private javax.swing.JTextField firstName;
    private javax.swing.JLabel firstNameLabel;
    private javax.swing.JTextField holdersName;
    private javax.swing.JTextField lastName;
    private javax.swing.JLabel lastNameLabel;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JLabel ownerLabel;
    private javax.swing.JTextField password;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables
}